<?php


namespace app\crm\model;

use app\admin\model\ShopOrderModel;
use app\admin\model\SysModel;
use app\mini\model\CustomerPointModel;
use app\shop\model\Order;
use app\shop\model\Refund;
use app\shop\model\ShopRefundOrderGoods;
use think\facade\Db;
use app\admin\model\Common;

class Service extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'service';


    /**
     * 获取顾客可用卡项
     * @param  array $request 请求参数
     * @return array
     */
    public function getCustomerService(array $request): array
    {
        $customer_id = $request['customer_id']??0;
        $goods_id = $request['goods_id']??0;
        $service = [];
        if(!empty($customer_id) && !empty($goods_id)){
            $service = $this->where('status',1)
                ->where('goods_id',$request['goods_id'])
                ->where('customer_id',$request['customer_id'])
                ->field('id,name,goods_alias_name,num,kk_money,consume_money,consume_gratuity')
                ->select()->toArray();
        }
        $data              = [];
        $data['list']      = $service ?? [];
        return $data;

    }


    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataList(array $request): array
    {

        // try {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        $customerId       = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : '';

        $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;


        $shopId = isset($request['shop_id']) && intval($request['shop_id']) ? intval($request['shop_id']) : 0;
        $shopIds = $request['shopIds'] ?? [];
        $where      = [];
        $mini = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

        if(empty($customerId)){
            $shopId && array_push($where, ['shop_id', '=', $shopId]);
            if($shopIds){
                array_push($where, ['shop_id', 'in', $shopIds]);
            }
        }

        if($mini == 0){
            $customerId && array_push($where, ['customer_id', '=', $customerId]);
        }else{
            $telephone222 = Db::name('customer')->where('id', '=', $customerId)->value('telephone');
            $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');
            array_push($where, ['customer_id', 'in', $customerIds222]);
        }

        array_push($where, ['status', '=', 1]);

        $start_time = $request['start_time'] ?? '';
        if($start_time){
            array_push($where, ['create_time', '>=', strtotime($start_time)]);
        }
        $end_time = $request['endTime'] ?? date('Y-m-d');
        if($end_time){
            array_push($where, ['create_time', '<=', strtotime($end_time." 23:59:59")]);
        }
        $customer_name = $request['customer_name'] ?? '';
        if($customer_name){
            $customerIds = Db::name('customer')->where('customer_name','like','%'.$customer_name.'%')->column('id');
            array_push($where, ['customer_id', 'in', $customerIds]);
        }
        $telephone = $request['telephone'] ?? '';
        if($telephone){
            $customerIds = Db::name('customer')->where('telephone','=',$telephone)->column('id');
            array_push($where, ['customer_id', 'in', $customerIds]);
        }
        $effective = $request['effective'] ?? 0;
        if($effective){
            $end_time = 24*60*60*$effective+time();
            array_push($where, ['end_time', '<=', $end_time]);
        }

        $card_name = isset($request['name']) ? $request['name'] : ''; //开卡名称
        if($card_name){
            array_push($where,['name','like',$card_name.'%']);
        }
        $shop_person_id = isset($request['shop_person_id']) ? $request['shop_person_id'] : 0;
//        $sysModel = new SysModel();
//        $position_id  = $sysModel->getPersonPositionId($shop_person_id);
//        if(!empty($position_id)){
//            array_push($where,['kk_user_id','=',$shop_person_id]);
//        }

//            array_push($where,['kk_money','=',0]);



        $dataCount = $this->where($where)->count();

        if ($dataCount) {
            $field = ['*'];

            if($is_export == '1'){

                if($shopId == '0'){

                    if($shopIds){
                        $list  = $this->where($where)->select()->toArray();
                    }else{
                        $list = [];
                    }

                    // $this->error = '请选择门店！！！';
                }else{

                    $list  = $this->where($where)->limit(450,50)->select()->toArray();
                }
                // $list  = $this->where($where)->select()->toArray();
                // ->field($field)->order('id DESC')
                // ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

            }else{
                $list  = $this->where($where)->field($field)->order('id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
            }

            $customerIdArr = array_values(array_unique(array_column($list, 'customer_id')));
            $customerWhere = [
                ['id', 'in', $customerIdArr]
            ];
            $customerList = Db::name('customer')->where($customerWhere)->column('customer_name,telephone', 'id');

            $sourceList = Db::name('customer')
                ->alias('c')
                ->join('xy_setting s', 'c.source_id = s.id')
                ->where([['c.id', 'in', $customerIdArr]])
                ->column('s.name as source_name', 'c.id');

            $kk_user_idArr = array_values(array_unique(array_column($list, 'kk_user_id')));
            $personList = Db::name('shop_person')->where('id','in',$kk_user_idArr)->column('name', 'id');

            $shop_idArr = array_values(array_unique(array_column($list, 'shop_id')));
            $shopList = Db::name('shop')->where('shop_id','in',$shop_idArr)->column('shop_name', 'shop_id');
            //查询登录员工是否是 门诊

            $loginstaffList = Db::name('admin_user')->where('id','=',$request['user_id'])->column('shop_id,id,realname');


            //获取登录员工的 部门归属
            $shopTypeList = Db::name('shop')->where('shop_id','=',$loginstaffList[0]['shop_id'])->column('shop_type,shop_id');


            $serviceIdArr = array_values(array_unique(array_column($list, 'id')));
            $map =[];
            if(!empty($request['user_shop_id'])){
                $map['is_cancel'] = 0;
            }
            $service_logList = Db::name('service_log')->where($map)->group('service_id')->column(['count(id)'], 'service_id');

            $serviceTypeArr = ['1' => '按期', '2' => '按次'];

            $shop_goods_category = DB::name('shop_goods_category')->column('name','id');


            foreach ($list as $key => $val) {
                $list[$key]['kk_money'] = bcadd($val['real_cancel_balance'],$val['real_cancel_gift'],2);
                $list[$key]['consume_money'] = $val['real_cancel_balance'];
                $list[$key]['consume_gratuity'] = $val['real_cancel_gift'];



                $goods_alias_name = $description = '';

                if($val['order_id']>0){
                    $description = DB::name('shop_order')->where('id',$val['order_id'])->value('description');
                    $goods_alias_name = $val['goods_alias_name'];
                    if(empty($val['goods_alias_name'])){
                        $goods_alias_name = DB::name('shop_order_goods')->where('order_id',$val['order_id'])->where('goods_id',$val['goods_id'])->value('goods_alias_name');
                        if(empty($goods_alias_name)){
                            $goods_alias_name=  DB::name('shop_order_goods')->where('id',$val['order_goods_id'])->value('goods_alias_name');
                        }
                    }
                }
                $list[$key]['category_name'] = isset($shop_goods_category[$val['category_id']]) ? $shop_goods_category[$val['category_id']]:'';
                $list[$key]['goods_alias_name']     = !empty($goods_alias_name)?$goods_alias_name:'';
                $list[$key]['description']     = !empty($description)?$description:'';
                $list[$key]['customer_name']     = isset($customerList[$val['customer_id']]) ?$customerList[$val['customer_id']]['customer_name']: '';
                $list[$key]['telephone']     = isset($customerList[$val['customer_id']]) ? $customerList[$val['customer_id']]['telephone']: "";
                $list[$key]['source_name']     = $sourceList[$val['customer_id']] ?? "";

                $list[$key]['create_time'] = date('Y-m-d', strtotime($val['create_time'])) ?? $val['create_time'];

                $list[$key]['service_type_name'] = $serviceTypeArr[$val['service_type']] ?? '';
                $list[$key]['last_service_time'] = $val['last_service_time'] ? date('Y-m-d H:i:s', $val['last_service_time']) : '';
                $list[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                $list[$key]['end_time']     = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                // $list[$key]['comment_time']     = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                $list[$key]['sy_num']       = $service_logList[$val['id']] ?? 0;
                $list[$key]['yy_num']       = bcsub($val['num'],$list[$key]['sy_num']);
                $list[$key]['kk_user_name'] = $personList[$val['kk_user_id']] ?? '';
                $list[$key]['shop_name'] = $shopList[$val['shop_id']] ?? '';

                $list[$key]['shop_type'] = $shopTypeList[0]['shop_type'] ?? '';

                //查询登录员工的归属信息
                if($mini == 0){
                    $logusershop = Db::name('admin_user')->alias('au')
                        ->join('shop_person sp', 'au.shop_person_id=sp.id', 'LEFT')
                        ->where('au.id','=',$request['user_id'])
                        ->where('au.is_status','=',0)
                        ->column('sp.shop_id as shopID,sp.id');

                    $list[$key]['shopid_U'] = $logusershop[0]['shopID'];
                }else{
                    $list[$key]['shopid_U'] = $val['shop_id'];
                }

                $shop_time = Db::name('shop_order')
                    ->where('uid',$val['customer_id'])
                    ->where('is_pay',1)
                    ->where('status',2)
                    ->order('deal_time','desc')
                    ->value('deal_time');
                $refund_time = Db::name('shop_refund_order')
                    ->where('uid',$val['customer_id'])
                    ->where('type',3)
                    ->where('refund_type','101.02')
                    ->where('status',2)
                    ->order('deal_time','desc')
                    ->value('deal_time');
                $service_time = Db::name('service_log')
                    ->where('customer_id',$val['customer_id'])
                    ->where('is_cancel',0)
                    ->order('create_time','desc')
                    ->value('create_time');

                // 过滤掉 NULL 值
                $validTimes = array_filter([$shop_time, $refund_time, $service_time], function($time) {
                    return !is_null($time);
                });

                if (!empty($validTimes)) {
                    $last_shop_time = date('Y-m-d', max($validTimes));
                }
                $list[$key]['last_shop_time'] = $last_shop_time ?? '';


            }
        }

        $is_show_xhcz = false;
        $shop_id = isset($request['user_shop_id']) && intval($request['user_shop_id']) ? intval($request['user_shop_id']) : 0;
        if(!empty($shop_id)){
            $shop_type = DB::name('shop')->where('shop_id',$shop_id)->value('shop_type');
            if($shop_type == 1){
                $is_show_xhcz = true;
            }
        }

        $data              = [];
        $data['isShowXhcz'] = $is_show_xhcz;
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
        // } catch (\Exception $e) {
        // }

//        $this->error = '暂无此数据';
//        return [];
    }


    /**
     * 添加
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataInfo(array $request): array
    {
        // try {
            $serviceId = $request['id'] ?? 0;
            if (!$serviceId) {
                $this->error = '参数错误';
                return [];
            }

            $info = $this->where('id', '=', $serviceId)->find();
            if (!$info) {
                $this->error = '暂无数据';
                return [];
            }
            $info = $info->toArray();
            $serviceTypeArr = ['1' => '按期', '2' => '按次'];
            $customerInfo   = Db::name('customer')->where('id', '=', $info['customer_id'])->find();
            $info['customer_name']     = $customerInfo['customer_name'] ?: '';
            $info['service_type_name'] = $serviceTypeArr[$info['service_type']] ?? '';
            $info['last_service_time'] = $info['last_service_time'] ? date('Y-m-d H:i:s', $info['last_service_time']) : '';
            $info['start_time']        = $info['start_time'] ? date('Y-m-d H:i:s', $info['start_time']) : '';
            $info['end_time']          = $info['end_time'] ? date('Y-m-d H:i:s', $info['end_time']) : '';

            $logWhere = [
                ['service_id', '=', $serviceId]
            ];
            $shopInfo   = Db::name('shop')->where('shop_id', '=', $info['shop_id'])->find();
            $logList = Db::name('service_log')->where($logWhere)->select()->toArray();
            if ($logList) {
                $oneId     = array_column($logList, 'nurse_id_one');
                $twoId     = array_column($logList, 'nurse_id_two');
                $userIdArr = array_unique(array_merge($oneId, $twoId));
                $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
                $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
                foreach ($logList as $key => $val) {
                    $logList[$key]['nurse_id_one_name'] = $userList[$val['nurse_id_one']] ?? '';
                    $logList[$key]['nurse_id_two_name'] = $userList[$val['nurse_id_two']] ?? '';
                    $logList[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $logList[$key]['end_time']          = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $logList[$key]['create_time']       = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '';
                    $logList[$key]['comment_time']      = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                    $logList[$key]['customer_name']     = $customerInfo['customer_name'];
                    $logList[$key]['sex']               = $customerInfo['sex'] == 1? '男':'女';
                    $logList[$key]['age']               = $customerInfo['age'];
                    $logList[$key]['shop_name']         = $shopInfo['shop_name'];
                    $logList[$key]['market_name']       = $shopInfo['market_name'];
                    $logList[$key]['nurse_name']        = $userList[$customerInfo['nurse_id']] ?? '';
                    $logList[$key]['name']        = $info['name'];
                    $logList[$key]['experience']  = $info['experience']==1?'体验':'服务';
                    $logList[$key]['pt']  = $val['pt']==1?'手机':'PC电脑';
                    $createName = Db::name('admin_user')->where('id','=',$val['create_id'])->value('realname');
                    $logList[$key]['createName']  = $createName ?? '';
                    $logList[$key]['fw_num']  = 1;
                }
            }
            $info['service_log'] = $logList;

            return $info;
        // } catch (\Exception $e) {
        // }

        return [];
    }
	/**

	 * 获取服务记录

	 * @param  array $request 请求参数

	 * @return array

	 */
	 public function getDataLog(array $request): array
    {
        $page = $request['page'] ?? 1;
        $pagesize = $request['pagesize'] ?? 10;
        $is_export = $request['export'] ?? 0;

        $where = [];
        $whereor = [];

        if (!empty($request['shopId'])) {
            $where[] = ['l.shop_id', '=', $request['shopId']];
        }

        if (!empty($request['is_cancel'])) {
            $where[] = ['l.is_cancel', 'in', $request['is_cancel']];
        }

        if (!empty($request['customer_id'])) {
            $where[] = ['l.customer_id', '=', $request['customer_id']];
        }

        if (!empty($request['customer_name'])) {
            $where[] = ['c.customer_name', 'like', '%' . $request['customer_name'] . '%'];
        }

        if (!empty($request['telephone'])) {
            $where[] = ['c.telephone', '=', $request['telephone']];
        }

        if (!empty($request['nurse_name'])) {
            $where[] = ['p1.name', 'like', '%' . $request['nurse_name'] . '%'];
            $whereor[] = ['p2.name', 'like', '%' . $request['nurse_name'] . '%'];
        }

        // 时间范围处理
        if (!empty($request['start_time']) || !empty($request['endTime'])) {
            $start = !empty($request['start_time']) ?
                strtotime($request['start_time'] . ' 00:00:00') : 0;

            $end = !empty($request['endTime']) ?
                strtotime($request['endTime'] . ' 23:59:59') : time();

            $where[] = ['l.create_time', 'between', [$start, $end]];
        }

        // 修复字段列表
        $field = '
            l.id,
            l.create_time,
            l.station_name,
            l.pt,
            l.is_cancel,
            l.mark,
            l.consume_money,
            l.consume_gratuity,
            l.real_cancel_gift,
            l.real_cancel_balance,
            a.realname as cancel_realname,
            c.customer_name,
            se.name,
            se.goods_alias_name,
            se.experience,
            se.num as fw_num,
            c.sex,
            c.age,
            s.shop_name,
            i1.name as item_one_name,
            i2.name as item_two_name,
            i3.name as item_three_name,
            p1.name as nurse_id_one_name,
            p2.name as nurse_id_two_name
        ';

        // 查询列表
        if ($is_export == 1) {
            $data = Db::name('service_log')
                ->alias('l')
                ->leftJoin('service se', 'se.id = l.service_id')
                ->leftJoin('customer c', 'c.id = l.customer_id')
                ->leftJoin('shop s', 's.shop_id = l.shop_id')
                ->leftJoin('shop_person p1', 'p1.id = l.nurse_id_one')
                ->leftJoin('shop_person p2', 'p2.id = l.nurse_id_two')
                ->leftJoin('item_type i1', 'i1.id = l.item_one')
                ->leftJoin('item_type i2', 'i2.id = l.item_two')
                ->leftJoin('item_type i3', 'i3.id = l.item_three')
                ->leftJoin('admin_user a', 'a.id = l.cancel_uid')
                ->field($field)
                ->where($where)
                ->whereOr($whereor)
                ->order('l.create_time', 'desc')
                ->select();
            if(!empty($data))
            {
                $data = json_decode(json_encode($data),1);
                // 直接处理数组结果
                foreach ($data as &$item)
                {
                    $item['consume_gratuity'] = $item['real_cancel_gift'];
                    $item['consume_money'] =   $item['real_cancel_balance'];
                    $item['create_time'] = $item['create_time'] ? date('Y-m-d', $item['create_time']) : "";
                    $item['status_msg'] = $item['is_cancel'] == 0 ? '正常' : ($item['is_cancel'] == 1 ? '员工作废' : '管理员作废');
                }
            }
        } else {
            $data = Db::name('service_log')
                ->alias('l')
                ->leftJoin('service se', 'se.id = l.service_id')
                ->leftJoin('customer c', 'c.id = l.customer_id')
                ->leftJoin('shop s', 's.shop_id = l.shop_id')
                ->leftJoin('shop_person p1', 'p1.id = l.nurse_id_one')
                ->leftJoin('shop_person p2', 'p2.id = l.nurse_id_two')
                ->leftJoin('item_type i1', 'i1.id = l.item_one')
                ->leftJoin('item_type i2', 'i2.id = l.item_two')
                ->leftJoin('item_type i3', 'i3.id = l.item_three')
                ->leftJoin('admin_user a', 'a.id = l.cancel_uid')
                ->field($field)
                ->where($where)
                ->whereOr($whereor)
                ->order('l.create_time', 'desc')
                ->paginate([
                    'list_rows' => $pagesize,
                    'page' => $page,
                    'query' => request()->param()
                ]);
            if(!empty($data))
            {
                $data = json_decode(json_encode($data),1);
                // 处理分页对象的数据部分
                foreach ($data['data'] as &$item)
                {
                    $item['consume_gratuity'] = $item['real_cancel_gift'];
                    $item['consume_money'] =   $item['real_cancel_balance'];
                    $item['create_time'] = $item['create_time'] ? date('Y-m-d', $item['create_time']) : "";
                    $item['status_msg'] = $item['is_cancel'] == 0 ? '正常' : ($item['is_cancel'] == 1 ? '员工作废' : '管理员作废');
                }
            }
        }

        return $data;
    }



	public function getDataLogImage(array $request)
    {
        $where = [];
        if (!empty($request['id'])) {
            $where[] = ['i.log_id', '=', $request['id']];
        }
        if (!empty($request['customer_id'])) {
            $where[] = ['i.customer_id', '=', $request['customer_id']];
        }

        // 修正字段列表 - 移除末尾的逗号
        $field = '
            i.id,
            i.service_id,
            i.log_id,
            i.shop_id,
            i.customer_id,
            i.img_url,
            i.create_time,
            c.customer_name,
            c.telephone,
            se.name,
            a.realname';

        $data = [];
        $data = Db::name('service_log_image')
                ->alias('i')
                ->leftJoin('service se', 'se.id = i.service_id')
                ->leftJoin('admin_user a', 'a.id = i.operator')
                ->leftJoin('customer c', 'c.id = i.customer_id')
                ->field($field)
                ->where($where)
                ->order('i.create_time', 'desc')
                ->select();
        if(!empty($data))
        {
            $data = json_decode(json_encode($data),1);
            foreach ($data as &$item)
            {
                $item['create_time'] = $item['create_time'] ? date('Y-m-d', $item['create_time']) : "";
                if(!empty($item['img_url']))
                {
                    $item['img_url'] = explode(',',$item['img_url']);
                }else
                {
                    $item['img_url'] = [];
                }
            }
        }

        return $data;
    }


	/**

	 * 获取员工护理量统计

	 * @param  array $request 请求参数

	 * @return array

	 */
	public function getDataNursing(array $request): array
	{

		$request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

		$request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;


		$shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

        $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;

		$shopIds = $request['shopIds'] ?? [];

		$nowYear =  date('y'); //当前年
		$nowMonth =  date('m'); //当前月份
		$nowdata =  date('t'); //当前天数

		$startmonth = $nowYear.'-'.$nowMonth.'-'.'1';
		$endmonth = $nowYear.'-'.$nowMonth.'-'.$nowdata;

		$start_time = $request['start_time'] ?? '';
		if($start_time){
			$startTimeToday =strtotime($request['start_time']);
		}else{
			$startTimeToday =strtotime($startmonth);
		}

		$endTime = $request['endTime'] ?? '';

		if($endTime){

			$endTimeToday =strtotime($request['endTime'])+86399;
			$startDataTime = strtotime($request['endTime']);
			$endDataTime = strtotime($request['endTime'])+86399;

		}else{
			$endTimeToday =strtotime($endmonth)+86399;
			$startDataTime = strtotime(date('Y-m-d'));
			$endDataTime = strtotime(date('Y-m-d'))+86399;
		}

		$where      = [];

        $shopId && array_push($where, ['s.shop_id', '=', $shopId]);

		if($shopIds){

			array_push($where,['s.shop_id','in',$shopIds]);

		}

		$nurseName = $request['nurse_name'] ?? '';

		if($nurseName){

			array_push($where,['s.name','=',$nurseName]);

		}

		$category =$this->getPushCategoryArray();
		array_push($where, ['s.status', '=', 1]);
		array_push($where, ['s.name', '<>', '虚拟员工核销专用']);

		$dataCount = Db::name('shop_person')->alias('s')
			    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
			    ->where($where)->count();

		/*
			疤痘护理---- 1  | 面部护理---- 8 | 项目身体护理  ---10  | 生命之源/经络通/疏肝理气 --11 | 基础补水 --12
		*/

		if ($dataCount) {

			$field = ['s.id,s.shop_id,s.shop_name,s.name,s.market_name,s.station_name'];

            if($is_export == '1'){

                $list  = Db::name('shop_person')->alias('s')

                    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                    ->where($where)

                    ->field($field)->order('s.shop_id DESC')

                    ->select()->toArray();

            }else{

                $list  = Db::name('shop_person')->alias('s')

                    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                    ->where($where)

                    ->field($field)->order('s.shop_id DESC')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->select()->toArray();

            }

			$pids =array_column($list,'id');
			$category =$this->getPushCategoryArray();
			$ids =array_column($category,'id');

            $bahennum = $mianbunum = $shentinum = $shengming = $jingluotong = $shuganliqi = $jichubushui= $total = $dayCount =[];
            foreach($list as $key=>&$v){

                $nurseCountT =$this->getNurseDateCount($v['id'],$startDataTime,$endDataTime);
                $huliTotal = 0;
                // 获取当天服务量
                // 比例为1的
                $public_where = [
                    ['category_id','in',$ids],
                    ['create_time','between',"$startTimeToday,$endTimeToday"],
                    ['shop_id','=',$v['shop_id']]
                ];
                $where = [];
                array_push($where,['nurse_id_one','=',$v['id']]);
                array_push($where,['nurse_id_two','=',0]);
                $arr1 =Db::name('service_log')->where($public_where)->where($where)->column('category_id');

                $arr1 =array_count_values($arr1);

                $count1 = isset($arr1[1])?$arr1[1]:0;
                $count4 = isset($arr1[4])?$arr1[4]:0;
                $count8 = isset($arr1[8])?$arr1[8]:0;
                $count10 = isset($arr1[10])?$arr1[10]:0;
                $count11 = isset($arr1[11])?$arr1[11]:0;
                $count12 = isset($arr1[12])?$arr1[12]:0;

                // 比例为0.5的
                $where = [];
                array_push($where,['nurse_id_one','=',$v['id']]);
                array_push($where,['nurse_id_two','>',0]);
                $arr2 =Db::name('service_log')->where($public_where)->where($where)->column('category_id');

                $where = [];
                array_push($where,['nurse_id_two','=',$v['id']]);
                array_push($where,['nurse_id_one','>',0]);
                $arr3 =Db::name('service_log')->where($public_where)->where($where)->column('category_id');
                $arr = array_merge($arr2,$arr3);
                $arr = array_count_values($arr);

                $data1 = isset($arr[1])?$arr[1]:0;
                $data4 = isset($arr[4])?$arr[4]:0;
                $data8 = isset($arr[8])?$arr[8]:0;
                $data10 = isset($arr[10])?$arr[10]:0;
                $data11 = isset($arr[11])?$arr[11]:0;
                $data12 = isset($arr[12])?$arr[12]:0;

                $v['bahennum'] = bcadd($count1,bcdiv($data1,2,1),1);
                $v['jingluotong'] = bcadd($count4,bcdiv($data4,2,1),1);
                $v['mianbunum'] = bcadd($count8,bcdiv($data8,2,1),1);
                $v['shentinum'] = bcadd($count10,bcdiv($data10,2,1),1);
                $v['shengming'] = bcadd($count11,bcdiv($data11,2,1),1);
                $v['shuganliqi'] = bcadd($count12,bcdiv($data12,2,1),1);

                //基础补水 没有办法归类暂时不做计算  2022-04-18
                $v['jichubushui'] = 0;


                $v['total'] = $v['bahennum']+$v['jingluotong']+$v['mianbunum']+$v['shentinum']+ $v['shengming']+$v['shuganliqi'];

                $v['daycount'] = $nurseCountT;

                array_push($bahennum,$v['bahennum']);
                array_push($mianbunum,$v['mianbunum']);
                array_push($shentinum,$v['shentinum']);
                array_push($shengming,$v['shengming']);
                array_push($jingluotong,$v['jingluotong']);
                array_push($shuganliqi,$v['shuganliqi']);
                array_push($jichubushui,$v['jichubushui']);

                array_push($total,$v['total']);
                array_push($dayCount, $v['daycount']);



            }

            $push_arr = [

                'market_name' => '汇总',
                'shop_name' => '',
                'name'=>'',
                'station_name'=>'',
                'daycount'=>array_sum($dayCount),
                'total'=>array_sum($total),
                'bahennum'=>array_sum($bahennum),
                'jingluotong'=>array_sum($jingluotong),
                'mianbunum'=>array_sum($mianbunum),
                'shentinum'=>array_sum($shentinum),
                'shengming'=>array_sum($shengming),
                'shuganliqi'=>array_sum($shuganliqi),
                'jichubushui'=>array_sum($jichubushui),
            ];
            array_push($list,$push_arr);
            $newsList = $list;
        }


		$data              = [];

		$data['service_log']      = $newsList ?? [];

		$data['dataCount']        = $dataCount ?? 0;

		return $data;

	}




    /**
     * 获取服务列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getLogList(array $request): array
    {
        try {
            $serviceId = $request['serviceId'] ?? 0;
            $customerId = $request['customerId'] ?? 0;
            if ($serviceId) {
                $logWhere = [
                    ['service_id', '=', $serviceId]
                ];
            }
            if ($customerId){
                $serviceIds = $this->where('customer_id', '=', $customerId)->column('id');
                $logWhere = [
                    ['service_id', 'in', $serviceIds]
                ];
            }
            // $logWhere['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            // $logWhere['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            // print_r($logWhere);exit;
            $logList = Db::name('service_log')->where($logWhere)->select()->toArray();
            if ($logList) {
                $oneId     = array_column($logList, 'nurse_id_one');
                $twoId     = array_column($logList, 'nurse_id_two');
                $userIdArr = array_unique(array_merge($oneId, $twoId));
                $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
                $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
                foreach ($logList as $key => $val) {
                    $logList[$key]['nurse_id_one_name'] = $userList[$val['nurse_id_one']] ?? '';
                    $logList[$key]['nurse_id_two_name'] = $userList[$val['nurse_id_two']] ?? '';
                    $logList[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $logList[$key]['end_time']          = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $logList[$key]['create_time']       = $val['create_time'] ? date('Y-m-d H:i:s', $val['create_time']) : '';
                    $logList[$key]['comment_time']       = $val['comment_time'] ? date('Y-m-d H:i:s', $val['comment_time']) : '';
                }
            }
            $info['service_log'] = $logList;

            return $info;
        } catch (\Exception $e) {

        }

        return [];
    }
    /**
     * 获取服务数据集
     */
    public function readServiceList(array $request): array
    {
        $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];
        $export = $request['export'] ?? 0;
        if ($export == 1){
            $ids = $request['id'] ?? [];
            array_push($where,['id','in',$ids]);
        }
        $shopIds = $request['shopIds'] ?? [];
        array_push($where,['id','in',$shopIds]);
        $list  = Db::name('service_log')->where($where)->order('id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
        $dataCount = Db::name('service_log')->where($where)->count();

        $serviceIds     = array_column($list, 'service_id');
        //获取服务列表
        $zlist = Db::name('service')->where([['id','in',$serviceIds]])->column(['id','name','shop_id','customer_id','service_type','num','start_time','end_time','create_time','last_service_time','status','experience'],'id');
        //获取店铺数据
        $shopIds     = array_column($list, 'shop_id');
        $shoplist = Db::name('shop')->where([['shop_id','in',$shopIds]])->column(['id','shop_name','shop_id','market_name'],'shop_id');
        //获取客户数据
        $customerIds     = array_column($list, 'customer_id');
        $customerlist = Db::name('customer')->where([['id','in',$customerIds]])->column(['id','customer_name','sex','age'],'id');
        //获取护理师
        $oneId     = array_column($list, 'nurse_id_one');
        $twoId     = array_column($list, 'nurse_id_two');
        $userIdArr = array_values(array_unique(array_merge($oneId, $twoId)));
        $userWhere = [
                    ['id', 'in', $userIdArr]
                ];
        $userList = Db::name('shop_person')->where($userWhere)->column('name', 'id');
        // 客户名称
        // 服务日期
        // 性别
        // 年龄
        // 门店
        // 市场
        // 卡项名称
        // 护理1
        // 护理2
        // 服务类型
        foreach ($list as $key => $val){
            // print_r($customerlist);exit();
            $list[$key]['customer_name']        = $customerlist[$val['customer_id']]['customer_name'] ?? "";
            $list[$key]['start_time']        = date('Y-m-d H:i:s',$list[$key]['start_time']);
            $list[$key]['sex']        = $customerlist[$val['customer_id']]['sex'] ?? 0;
            $list[$key]['age']        = $customerlist[$val['customer_id']]['age'] ?? 0;
            $list[$key]['shop_name']        = $shoplist[$val['shop_id']]['shop_name'] ?? "";
            $list[$key]['market_name']        = $shoplist[$val['shop_id']]['market_name'] ?? "";
            $list[$key]['name']        = $zlist[$val['service_id']]['name'] ?? "";
            $list[$key]['nurse_id_name']        = $userList[$val['nurse_id_one']] ?? "";
            if (isset($userList[$val['nurse_id_two']])){
                $list[$key]['nurse_id_name'] = $list[$key]['nurse_id_name'].'，'.$userList[$val['nurse_id_two']];
            }
            $list[$key]['service_type']        = $zlist[$val['service_id']]['service_type'] ?? 1;
        }

        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return $data;
    }

    /**
     * 新增服务记录-中台核销
     */
    public function addServiceLog(array $request): array
    {

        Db::startTrans();
        try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                throw new \Exception("数据格式错误");
            }

            $serviceData = $serviceInfo = $this->where('id','=',$serviceId)->find();
            $num = $request['num'] ?? 0;
            if($num == 0){
                throw new \Exception("服务次数不能为0");
            }
            //已经核销的次数
            $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->where('is_cancel',0)->count() ?? 0;
            if(bcadd($num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                throw new \Exception("超过服务次数无法进行核销");
            }

            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            if($nurse_id_one == 0){
                throw new \Exception("请选择一号护理师");
            }
            $customer_id = $request['customer_id'] ?? 0;

            if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                throw new \Exception("服务客户错误");
            }

            $shop_id = $request['shop_id'] ?? 0;
            $shop = DB::name('shop')->where('shop_id',$shop_id)->where('status',1)->field('shop_type,shop_id')->find();
            if(empty($shop)){
                throw new \Exception("门店信息不存在");
            }

            $needNoZeronum = $serviceData['num']-$sy_num;

            //获取单次消耗和最后一次消耗
            list($consume_money,$consume_gratuity,$last_money,$last_gift,$once_discount,$last_discount_amount,$once_real_balance,$once_real_gift,$last_real_balance,$last_real_gift) = $this->lasttimeConsume($serviceData);

            $cancel_time = time();

            for($i=1;$i<=$num;$i++){
                    $addData = [];
                    $addData['consume_money'] = $addData['consume_gratuity'] = $addData['discount_amount'] = 0;
                    if($needNoZeronum == 1){
                        $addData['consume_money'] = $last_money ;
                        $addData['consume_gratuity'] = $last_gift;
                        $addData['discount_amount'] = $last_discount_amount;
                        $addData['real_cancel_balance'] = $last_real_balance;
                        $addData['real_cancel_gift'] = $last_real_gift;
                    }
                    else{
                        if($i<$needNoZeronum){
                            $addData['consume_money'] = $consume_money;
                            $addData['consume_gratuity'] = $consume_gratuity;
                            $addData['discount_amount'] = $once_discount;
                            $addData['real_cancel_balance'] = $once_real_balance;
                            $addData['real_cancel_gift'] = $once_real_gift;
                        }
                        elseif($i==$needNoZeronum){
                            $addData['consume_money'] = $last_money;
                            $addData['consume_gratuity'] = $last_gift;
                            $addData['discount_amount'] = $last_discount_amount;
                            $addData['real_cancel_balance'] = $last_real_balance;
                            $addData['real_cancel_gift'] = $last_real_gift;
                        }
                    }
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $request['nurse_id_one'] ?? 0;
                    $addData['nurse_id_two']= $request['nurse_id_two'] ?? 0;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;
                    $addData['comment_time']    = isset($request['comment_time']) ? strtotime($request['comment_time']) : 0;;
                    $addData['create_time'] = $cancel_time;
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id;
                    $addData['pt']     = $request['pt'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'];
                    $addData['item_one']    = $serviceInfo['category_type_one'];
                    $addData['item_two']    = $serviceInfo['category_type_two'];
                    $addData['item_three']  = $serviceInfo['category_type_three'];

                    $service_log_id = Db::name('service_log')->insertGetId($addData);
                }

            $saveCustomer['final_service'] = time();
            Db::name('customer')->where('id','=',$addData['customer_id'])->update($saveCustomer);
            if (bcadd($num,$sy_num) == $serviceInfo['num']) {
                $saveData = [
                    'status'=>2,
                    'gb_end_time'=>time(),
                ];
                $this->where('id','=',$serviceId)->save($saveData);
            }

            Db::commit();
            $this->error = '添加服务记录成功';
            return ['id'=>0];
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];
        }
    }

    //获取服务卡项订单信息
    public function getServiceOrder($serviceInfo){
        $shopOrder = ShopOrderModel::where('id',$serviceInfo['order_id'])->find();
        $shopRefundOrderGoods = ShopOrderGoods::where('id',$serviceInfo['order_goods_id'])->find();
        $cjyh = ShopOrderGoods::where('order_id',$serviceInfo['order_id'])->where('kingdee_code','101.12.098')->find();
        return [$shopOrder,$shopRefundOrderGoods,$cjyh];
    }

    //获取服务卡项折扣价格-暂时不用
    public function getServiceLogGiscounts($serviceInfo){

        list($shopOrder,$shopRefundOrderGoods,$cjyh) = $this->getServiceOrder($serviceInfo);

        //已经优惠/多卖的价格
        $servicelogData  = ServiceLog::where('service_id',$serviceInfo['id'])->where('is_cancel',0)->field('discount_amount,consume_money,consume_gratuity')->select()->toArray();

        $aleryDiscounts = bcadd(array_sum(array_column($servicelogData,'discount_amount')),0,2);
        $aleryConsumeMoney = bcadd(array_sum(array_column($servicelogData,'consume_money')),0,2);
        $aleryConsumeGratuity = bcadd(array_sum(array_column($servicelogData,'consume_gratuity')),0,2);

        //已经核销过的次数
        $aleryCancelCount = count($servicelogData);

        //剩余次数
        $surplus_num = bcsub($serviceInfo['num'],$aleryCancelCount);
        $surplus_discounts_amount  = bcsub(bcmul($cjyh['pay_price'],$cjyh['num'],2),$aleryDiscounts,2);//剩余未优惠金额

        $surplusConsumeMoney    =    bcsub($serviceInfo['consume_money'],$aleryConsumeMoney,2);        //剩余消耗本金
        $surplusConsumeGratuity =    bcsub($serviceInfo['consume_gratuity'],$aleryConsumeGratuity,2);   //剩余消耗赠金


        if($surplus_num == 1){
            $one_discount = $surplus_discounts_amount;
            $one_balance = $surplusConsumeMoney;
            $one_gift = $surplusConsumeGratuity;
        }else{
            $one_discount = bcdiv($surplus_discounts_amount,$surplus_num,2);
            $one_balance  = bcdiv($surplusConsumeMoney,$surplus_num,2);;
            $one_gift     = bcdiv($surplusConsumeGratuity,$surplus_num,2);;
        }

        return [$shopOrder,$shopRefundOrderGoods,$cjyh,$one_discount,$one_balance,$one_gift];
    }





    /**
     * 获取服务卡项，最后一次消耗及单次消耗
     *    $benyueCancel 本月最大消耗数
     *    $needNoZeronum 应该核销次数
     **/
    public function lasttimeConsume($serviceData){

        $service_gift  = $serviceData['consume_gratuity']; //开卡时，消耗赠金
        $service_money = $serviceData['consume_money'];  //开卡时，消耗的本金
        $service_discount = $serviceData['discount_amount'];  //开卡时，优惠的金额
        $real_cancel_balance = $serviceData['real_cancel_balance'];  //开卡时，真实消耗的本金
        $real_cancel_gift = $serviceData['real_cancel_gift'];  //开卡时，真实消耗的赠金

        $maxServiceNum = $serviceData['service_max_num'];    //最大进店次数

        $serviceLog = ServiceLog::where('service_id',$serviceData['id'])
            ->where('is_cancel',0)
            ->field('sum(consume_money) as consume_money,sum(consume_gratuity) as consume_gratuity,sum(discount_amount) as discount_amount,sum(real_cancel_balance) as real_balance,sum(real_cancel_gift) as real_gift,count(id) as count')->find();
        //已经消耗的本金-赠金-优惠价格-核销次数
        $yet_cancel_count = 0;
        if(!empty($serviceLog['consume_money'])){
            $yet_cancel_count = $serviceLog['count'];
            $service_money = bcsub($service_money,$serviceLog['consume_money'],2);
            $service_gift = bcsub($service_gift,$serviceLog['consume_gratuity'],2);
            $service_discount = bcsub($service_discount,$serviceLog['discount_amount'],2);
            $real_cancel_balance = bcsub($real_cancel_balance,$serviceLog['real_balance'],2);
            $real_cancel_gift = bcsub($real_cancel_gift,$serviceLog['real_gift'],2);
        }
        $maxServiceNum = bcsub($maxServiceNum,$yet_cancel_count); //最大进店次数;

        $once_cancel_balance   =   $maxServiceNum >0  ?   bcdiv($service_money, $maxServiceNum, 2): 0; //单次消耗的本金
        $once_cancel_gift      =   $maxServiceNum >0  ?   bcdiv($service_gift, $maxServiceNum, 2) : 0; //单次消耗的赠金
        $once_discount_amount  =   $maxServiceNum >0  ?   bcdiv($service_discount, $maxServiceNum, 2): 0; //单次优惠的金额
        $once_real_cancel_balance  =  $maxServiceNum >0 ? bcdiv($real_cancel_balance, $maxServiceNum, 2): 0; //单次真实消耗本金
        $once_real_cancel_gift  =   $maxServiceNum >0 ? bcdiv($real_cancel_gift, $maxServiceNum, 2): 0; //单次真实消耗赠金

        if($serviceData['service_type'] == 1){
            //疗程卡
            $last_balance = bcsub($service_money,bcmul(bcsub($maxServiceNum,1),$once_cancel_balance,2),2);  //最后一次消耗本金;
            $last_gift  = bcsub($service_gift,bcmul(bcsub($maxServiceNum,1),$once_cancel_gift,2),2);  //最后一次消耗赠金;
            $last_discount_amount = bcsub($service_gift,bcmul(bcsub($maxServiceNum,1),$once_discount_amount,2),2);  //最后一次优惠价格;
            $last_real_cancel_balance = bcsub($service_money,bcmul(bcsub($maxServiceNum,1),$once_real_cancel_balance,2),2);  //最后一次消耗本金;
            $last_real_cancel_gift  = bcsub($service_gift,bcmul(bcsub($maxServiceNum,1),$once_real_cancel_gift,2),2);  //最后一次消耗赠金;
        }else{
            //次卡
            if($serviceData['num'] >0){
                $last_balance =  bcsub($service_money,bcmul(bcsub($maxServiceNum,1),$once_cancel_balance,2),2);//最后一次消耗本金;
                $last_gift  =   bcsub($service_gift,bcmul(bcsub($maxServiceNum,1),$once_cancel_gift,2),2);//最后一次消耗赠金;
                $last_discount_amount =  bcsub($service_discount,bcmul(bcsub($maxServiceNum,1),$once_discount_amount,2),2);//最后一次优惠价格;
                $last_real_cancel_balance = bcsub($real_cancel_balance,bcmul(bcsub($maxServiceNum,1),$once_real_cancel_balance,2),2);  //最后一次消耗本金;
                $last_real_cancel_gift  = bcsub($real_cancel_gift,bcmul(bcsub($maxServiceNum,1),$once_real_cancel_gift,2),2);  //最后一次消耗赠金;
            }
        }
        return [$once_cancel_balance,$once_cancel_gift,$last_balance,$last_gift,$once_discount_amount,$last_discount_amount,$once_real_cancel_balance,$once_real_cancel_gift,$last_real_cancel_balance,$last_real_cancel_gift];
    }


    //获取出库单-商品对应的护理师12及服务项12
    public function getOrderGoodsInfo($order_id,$order_goods_id){
        var_dump($order_id,$order_goods_id);die;
        $data = DB::name('shop_order_goods')
            ->where(['order_id'=>$order_id,'goods_id'=>$order_goods_id])
            ->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project,id')
            ->find();
        if(!empty($data)){
             $shop_order_goods_option_data = DB::name('shop_order_goods_option_log')
            ->where(['order_id'=>$order_id,'shop_order_goods_id'=>$data['id'],'is_new'=>1])
            ->field('nurse_one,nurse_one_project,nurse_two,nurse_two_project')
            ->find();

            if(!empty($shop_order_goods_option_data)){
                return $shop_order_goods_option_data;
            }
        }
        return $data;

    }

    public function getMonthEnterShopNum($logData,$serviceData){

        $cancel_time = $logData['create_time'];

        //核销的年份
        $year_cancel = date('Y',$cancel_time);
        //核销的月份
        $month_cancel = date('m',$cancel_time);
        $yearMonthCancel = date('Ym',$cancel_time);

        //服务开始时间
        $service_begin_time = $serviceData['start_time'];
        $service_begin_time_year = date('Y',$service_begin_time);

        $service_begin_time_month = date('m',$service_begin_time);
        $service_begin_time_yearMonth = date('Ym',$service_begin_time);

        //服务结束时间
        $service_end_time = $serviceData['end_time'];
        $service_end_time_year = date('Y',$service_end_time);

        $service_end_time_month = date('m',$service_end_time);
        $service_end_time_yearMonth = date('Ym',$service_end_time);

        if($service_begin_time_yearMonth == $service_end_time_yearMonth ){
            //服务卡项-开始时间和结束时间是同月份
            $max_cancel_num = $serviceData['first_month_max_service_num'];
        }else{
            //服务卡项-开始时间和结束时间是同年但不同月份的
            if($service_begin_time_year == $service_end_time_year){
                //核销月份与开卡日期是同月份取第一个月
                if($month_cancel == $service_begin_time_month ){
                    $max_cancel_num = $serviceData['first_month_max_service_num'];
                }elseif($month_cancel == $service_end_time_month){
                    //核销月份与开卡结束月份是同一个月，取最后一个月
                    $max_cancel_num = $serviceData['end_month_max_service_num'];
                }else{
                    //否则取中间
                    $max_cancel_num = $serviceData['middle_month_max_service_num'];
                }
            }else{
                //跨年
                if($year_cancel < $service_end_time_year){
                    if($service_begin_time_yearMonth ==  $yearMonthCancel){
                        $max_cancel_num = $serviceData['first_month_max_service_num'];
                    }else{
                        $max_cancel_num = $serviceData['middle_month_max_service_num'];
                    }
                }else{
                    if($year_cancel == $service_begin_time_year){
                        if($month_cancel == $service_begin_time_month){
                            $max_cancel_num = $serviceData['first_month_max_service_num'];
                        }else{
                            $max_cancel_num = $serviceData['middle_month_max_service_num'];
                        }
                    }
                    elseif($year_cancel == $service_end_time_year){
                        if($month_cancel == $service_end_time_month){
                            $max_cancel_num = $serviceData['end_month_max_service_num'];
                        }else{
                            $max_cancel_num = $serviceData['middle_month_max_service_num'];
                        }
                    }
                    else{
                        if($month_cancel == 1){
                            $max_cancel_num = $serviceData['first_month_max_service_num'];
                        }elseif($month_cancel == 12){
                            $max_cancel_num = $serviceData['middle_month_max_service_num'];
                        }else{
                            $max_cancel_num = $serviceData['end_month_max_service_num'];
                        }
                    }
                }


            }
        }
        return $max_cancel_num;
    }
        /**
     * 新增服务记录
     */
    public function addServiceLog2(array $request): array
    {
        // try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                $this->error = '数据格式错误';
                return [];
            }
            $serviceInfo = $this->where('id','=',$serviceId)->find();
            if(empty($serviceInfo)){
                $this->error = '服务不存在';
                return [];
            }
            if($serviceInfo['service_type'] == 1){
                if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                    $this->error = '不在服务时间内，无法进行核销';
                    return [];
                }
            }
            $num = $request['num'] ?? 0;
            if($num == 0){
                $this->error = '服务次数不能为0';
                return [];
            }
            $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
            if(bcadd($num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                $this->error = '超过服务次数无法进行核销';
                return [];
            }
            $key = $request['key'] ?? 0;
            if($key == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('service_id','=',$serviceId)->order('id desc')->find();
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $key){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            for($i=1;$i<=$num;$i++){
                $addData = [];
                $addData['service_id']  = $serviceId;
                $addData['nurse_id_one']= $request['nurse_id_one'] ?? 0;
                $addData['nurse_id_two']= $request['nurse_id_two'] ?? 0;
                $addData['start_time']  = isset($request['start_time']) ? strtotime($request['start_time']) : 0;
                $addData['end_time']    = isset($request['end_time']) ? strtotime($request['end_time']) : 0;;
                $addData['create_time'] = time();
                $addData['customer_id'] = $request['customer_id'] ?? 0;
                $addData['shop_id']     = $request['shop_id'] ?? 0;
                $addData['pt']          = $request['pt'] ?? 0;
                $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                $addData['key']         = $key;
                $addData['status']      = 0;
                array_push($addDataAll,$addData);
            }

            if($addData['nurse_id_one'] == 0){
                $this->error = '请选择一号护理师';
                return [];
            }
            if($addData['customer_id'] == 0 || $addData['customer_id'] != $serviceInfo['customer_id']){
                $this->error = '服务客户错误';
                return [];
            }
            // if($addData['start_time'] = 0 || $addData['end_time'] = 0){
            //     $this->error = '请选择服务的开始时间和结束时间';
            //     return [];
            // }
            // if($addData['start_time'] > $addData['end_time']){
            //     $this->error = '开始时间不能大于结束时间';
            //     return [];
            // }

            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        // } catch (\Exception $e) {
        //     $this->error = '添加服务记录失败';
        //     return [];
        // }
    }
     /**
     * 新增服务记录
     */
    public function gbservice(array $request): array
    {
        try{
            $serviceId = $request['service_id'] ?? 0;
            if ($serviceId == 0){
                $this->error = '数据格式错误';
                return [];
            }
            $serviceInfo = $this->where('id','=',$serviceId)->find();

            $saveData = [
                    'gb_user_id'=>$request['user_id'],
                    'status'=>3,
                    'gb_end_time'=>time()
                ];
            $this->where('id','=',$serviceId)->save($saveData);
            $this->error = '服务已关闭';
            CustomerPointModel::pointChange($serviceInfo['customer_id'],5);
            return ['id'=>$serviceId];
        } catch (\Exception $e) {
            $this->error = '服务关闭失败';
            return [];
        }
        // return [];
    }

         /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getNoUseDataList(array $request): array
    {
        try {
            $customerId       = isset($request['customer_id']) && intval($request['customer_id']) ? intval($request['customer_id']) : '';
            $serverIds       = $request['serverIds'] ??  '';
            if(empty($customerId)){
                $this->error = '客户数据不存在';
                return [];
            }
            $nurseId       = isset($request['nurse_id']) && intval($request['nurse_id']) ? intval($request['nurse_id']) : '';
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;
            //核验客户和员工是否是同一家店
            $personInfo = Db::name('shop_person')->where('id','=',$nurseId)->find();
            $customerInfo = Db::name('customer')->where('id','=',$customerId)->find();
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = $customerInfo['telephone'];
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                // print_r($customerList);exit;
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customerId = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if($customerInfo['shop_id'] != $personInfo['shop_id']){
                $this->error = '非本店客户，无法进行核销';
                return [];
            }
            $where = [];
            //处理过期的数据
            array_push($where,['customer_id','=',$customerId]);
            array_push($where,['service_type','=',1]);
            array_push($where,['end_time','<=',time()]);
            $this->where($where)->update(['status'=>2]);
            $where = [];
            array_push($where,['customer_id','=',$customerId]);
            array_push($where,['status','=',1]);
            if(!empty($serverIds)){
                array_push($where,['id','in',explode(',',$serverIds)]);
            }
            // array_push($where,['start_time','>=',time()]);
            // array_push($where,['end_time','<=',time()]);
            // print_r($serverIds);exit;
            $list  = $this->where($where)->order('id DESC')->select()->toArray();
            // print_r($list);exit;

            // echo "<pre>";
            // print_r($where);
            // echo "</pre>";
            // exit;
            if($list){
                 $shop_idArr = array_values(array_unique(array_column($list, 'shop_id')));
                $shopList = Db::name('shop')->where('shop_id','in',$shop_idArr)->column('shop_name', 'shop_id');
                $serviceIdArr = array_values(array_unique(array_column($list, 'id')));
                $service_logList = Db::name('service_log')->group('service_id')->column(['count(id)'], 'service_id');
                $serviceTypeArr = ['1' => '按期', '2' => '按次'];
                foreach ($list as $key => $val) {
                    if($val['service_type'] == 1 && $val['start_time']>time()){
                        continue;
                    }
                    $name = '';
                    if(!empty($val['order_id'])){
                        $name = DB::name('shop_order_goods')->where('order_id',$val['order_id'])->where('goods_id',$val['goods_id'])->value('goods_alias_name');
                    }

                    $list[$key]['name'] = empty($name)?$val['name']:$val['name'].'-('.$name.')';
                    $list[$key]['service_type_name'] = $serviceTypeArr[$val['service_type']] ?? '';
                    $list[$key]['last_service_time'] = $val['last_service_time'] ? date('Y-m-d H:i:s', $val['last_service_time']) : '';
                    $list[$key]['start_time']        = $val['start_time'] ? date('Y-m-d H:i:s', $val['start_time']) : '';
                    $list[$key]['end_time']     = $val['end_time'] ? date('Y-m-d H:i:s', $val['end_time']) : '';
                    $list[$key]['sy_num']       = $service_logList[$val['id']] ?? 0;
                    $list[$key]['yy_num']       = bcsub($val['num'],$list[$key]['sy_num']);
                }
                $list = array_values($list);
            }
            $data              = [];
            $data['list']      = $list ?? [];
            return $data;
        } catch (\Exception $e) {
            $this->error = '服务列表为空2';
            return [];
        }
        $this->error = '服务列表为空';
        return [];
    }

    /**
     * 新增服务记录
     */
    public function addServiceLog3(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        try{
            // $add = [
            //         [
            //             'service_id'    =>26,
            //             'fw_num'        =>28,
            //         ],
            //         [
            //             'service_id'    =>25,
            //             'fw_num'        =>28,
            //         ]
            //     ];

            //     print_r(json_encode($add));exit;

            $serviceList = $request['serviceList'] ?? [];
            // $serviceList = $add;
            $keys = $request['key'] ?? '';
            // print_r($key);exit;
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            // mark 备注
            $mark = $request['mark'] ?? 0;

            $bookId = $request['bookId'] ?? 0;
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            // $shop_id = $request['shop_id'] ?? 0;
            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }
            // print_r($serviceList);exit;
            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                // print_r($customerList);exit;
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            // print_r($cunzaikeyFind);exit;
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            foreach ($serviceList as $key => $val){
                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    // code...
                    $this->error = '请录入服务记录';
                    return [];
                }
                $serviceInfo = $this->where('id','=',$serviceId)->find();
                if(empty($serviceInfo)){
                    $num = bcadd($key,1);
                    $this->error = '第【'.$num.'】条服务不存在';
                    return [];
                }
                if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                    $this->error = '服务客户错误';
                    return [];
                }
                if($serviceInfo['service_type'] == 1){
                    if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                        $this->error = '不在服务时间内，无法进行核销';
                        return [];
                    }
                }
                if($fw_num == 0){
                    $this->error = '服务次数不能为0';
                    return [];
                }
                $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                    $this->error = '超过服务次数无法进行核销';
                    return [];
                }
                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    array_push($addDataAll,$addData);
                }

            }

            // xy_book_uselog 预约数据核销记录表
            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";

            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($updateUseLog);
                // echo "</pre>";

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);

                // echo "111";echo "<br/>";
                // var_dump($bool);

            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($addUseLog);
                // echo "</pre>";


                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

                // echo "222";echo "<br/>";
                // var_dump($log_id);

            }

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";
            // exit;

            // $cunzaikeyFind = Db::name('service_log_mini')->where('service_id','=',$serviceId)->order('id desc')->find();
            // $cunzaikey = $cunzaikeyFind['key'] ?? '';
            // if($cunzaikey != $key){
            //     $this->error = '客户已更新服务二维码，请重新扫码';
            //     return [];
            // }


            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            // print_r($addDataAll);exit;
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        } catch (\Exception $e) {
            $this->error = '添加服务记录失败';
            return [];
        }
    }


    public function addServiceLog5(array $request): array
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        // try{
            // $add = [
            //         [
            //             'service_id'    =>26,
            //             'fw_num'        =>28,
            //         ],
            //         [
            //             'service_id'    =>25,
            //             'fw_num'        =>28,
            //         ]
            //     ];

            //     print_r(json_encode($add));exit;
            $serviceList = $request['serviceList'] ?? [];
            // $serviceList = $add;
            $keys = $request['key'] ?? '';
            // print_r($key);exit;
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            // mark 备注
            $mark = $request['mark'] ?? 0;

            $bookId = $request['bookId'] ?? 0;
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            // $shop_id = $request['shop_id'] ?? 0;
            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }
            // print_r($serviceList);exit;
            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }
            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }
            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            //todo
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }
            $addDataAll = [];
            foreach ($serviceList as $key => $val){
                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    // code...
                    $this->error = '请录入服务记录';
                    return [];
                }
                $serviceInfo = $this->where('id','=',$serviceId)->find();
                if(empty($serviceInfo)){
                    $num = bcadd($key,1);
                    $this->error = '第【'.$num.'】条服务不存在';
                    return [];
                }
                if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                    $this->error = '服务客户错误';
                    return [];
                }
                if($serviceInfo['service_type'] == 1){
                    if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                        $this->error = '不在服务时间内，无法进行核销';
                        return [];
                    }
                }
                if($fw_num == 0){
                    $this->error = '服务次数不能为0';
                    return [];
                }
                $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                    $this->error = '超过服务次数无法进行核销';
                    return [];
                }
                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;
                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    array_push($addDataAll,$addData);
                }

            }

            // xy_book_uselog 预约数据核销记录表
            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";

            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($updateUseLog);
                // echo "</pre>";

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);

                // echo "111";echo "<br/>";
                // var_dump($bool);

            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                // echo "<pre>";
                // print_r($addUseLog);
                // echo "</pre>";


                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

                // echo "222";echo "<br/>";
                // var_dump($log_id);

            }

            // echo "<pre>";
            // print_r($book_uselog);
            // echo "</pre>";
            // exit;

            // $cunzaikeyFind = Db::name('service_log_mini')->where('service_id','=',$serviceId)->order('id desc')->find();
            // $cunzaikey = $cunzaikeyFind['key'] ?? '';
            // if($cunzaikey != $key){
            //     $this->error = '客户已更新服务二维码，请重新扫码';
            //     return [];
            // }


            // if (bcadd($num,$sy_num) == $serviceInfo['num']) {
            //     $saveData = [
            //         'status'=>2,
            //         'gb_end_time'=>time(),
            //     ];
            //      $this->where('id','=',$serviceId)->save($saveData);
            // }
            // print_r($addDataAll);exit;
            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];
        // } catch (\Exception $e) {
        //     $this->error = '添加服务记录失败';
        //     return [];
        // }
    }

    // 核销测试
    public function addServiceLogCeshi(array $request): array
    {

            $serviceList = $request['serviceList'] ?? [];
            $service_type = $request['type'] ?? [];
            $keys = $request['key'] ?? '';
            $customer_id = $request['customer_id'] ?? 0;
            $nurse_id_one = $request['nurse_id_one'] ?? 0;
            $nurse_id_two = $request['nurse_id_two'] ?? 0;

            $mark = $request['mark'] ?? 0;
            $bookId = $request['bookId'] ?? 0; //预约id
            $mini       = isset($request['mini']) && intval($request['mini']) ? intval($request['mini']) : 0;

            if (empty($serviceList)){
                $this->error = '请录入服务记录';
                return [];
            }

            if($keys == 0){
                $this->error = '服务不存在，请重新扫码';
                return [];
            }
            $personInfo = Db::name('shop_person')->where('id','=',$nurse_id_one)->find();
            if (empty($nurse_id_one) || empty($personInfo)) {
                    // code...
                $this->error = '请选择一号护理师';
                return [];
            }
            if (!empty($nurse_id_two) && $nurse_id_two == $nurse_id_one) {
                    // code...
                $this->error = '二号护理师不能和一号护理师相同';
                return [];
            }

            if($mini == 0){
                // $customerId && array_push($where, ['customer_id', '=', $customerId]);
            }else{
                $telephone222 = Db::name('customer')->where('id','=',$customer_id)->value('telephone');
                $customerList = Db::name('customer')->where('telephone', '=', $telephone222)->select()->toArray();
                foreach ($customerList as $key => $val){
                    if($val['shop_id'] == $personInfo['shop_id']){
                        $customerInfo = $val;
                        $customer_id = $val['id'];
                    }
                }
                // array_push($where, ['customer_id', 'in', $customerIds222]);
            }

            if(empty($customerInfo)||empty($personInfo)){
                $this->error = '客户数据不存在';
                return [];
            }
            $shop_id = $customerInfo['shop_id'];
            $cunzaikeyFind = Db::name('service_log_mini_key')->where('customer_id','=',$customer_id)->order('id desc')->find();
            //todo
            $cunzaikey = $cunzaikeyFind['key'] ?? '';
            if($cunzaikey != $keys){
                $this->error = '客户已更新服务二维码，请重新扫码';
                return [];
            }

            $addDataAll = [];

            foreach ($serviceList as $key => $val){

                $serviceId = $val['service_id'] ?? 0;
                $fw_num = $val['fw_num'] ?? 0;
                $controlList = isset($val['controlList'])?json_encode($val['controlList']):'';
                $serviceId = intval($serviceId);
                $fw_num = intval($fw_num);
                if (empty($serviceId) || empty($fw_num)) {
                    $this->error = '请录入服务记录';
                    return [];
                }
                if($service_type == 1){
                    if($fw_num == 0){
                        $this->error = '服务次数不能为0';
                        return [];
                    }
                    $serviceInfo = $this->where('id','=',$serviceId)->find();
                    if(empty($serviceInfo)){
                        $num = bcadd($key,1);
                        $this->error = '第【'.$num.'】条服务不存在';
                        return [];
                    }
                    if($customer_id == 0 || $customer_id != $serviceInfo['customer_id']){
                        $this->error = '服务客户错误';
                        return [];
                    }
                    if($serviceInfo['service_type'] == 1){
                        if ($serviceInfo['start_time'] > time() || $serviceInfo['end_time'] < time()){
                            $this->error = '不在服务时间内，无法进行核销';
                            return [];
                        }
                    }

                    $sy_num = Db::name('service_log')->where('service_id','=',$serviceId)->count() ?? 0;
                    if(bcadd($fw_num,$sy_num)>$serviceInfo['num'] && $serviceInfo['service_type'] == 2){
                        $this->error = '超过服务次数无法进行核销';
                        return [];
                    }

                }

                for($i=1;$i<=$fw_num;$i++){
                    $addData = [];
                    $addData['service_id']  = $serviceId;
                    $addData['nurse_id_one']= $nurse_id_one;
                    $addData['nurse_id_two']= $nurse_id_two;

                    $addData['start_time']  = 0;
                    $addData['end_time']    = 0;;
                    $addData['create_time'] = time();
                    $addData['customer_id'] = $customer_id;
                    $addData['shop_id']     = $shop_id ?? 0;
                    $addData['pt']          = 1;
                    $addData['category_id'] = $serviceInfo['category_id'] ?? 0;
                    $addData['goods_id']    = $serviceInfo['goods_id'] ?? 0;
                    $addData['key']         = $keys;
                    $addData['status']      = 0;
                    $addData['mark']        = $mark;
                    $addData['service_type']= $service_type;
                    $addData['control_str'] = $controlList;
                    array_push($addDataAll,$addData);
                }

            }





            $where_book_uselog = [];

            array_push($where_book_uselog,['book_id','=',$bookId]);

            $book_uselog = Db::name('books_uselog')->where($where_book_uselog)->select()->toArray();


            if(!empty($book_uselog)){

                $updateUseLog = [

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];

                $bool = Db::name('books_uselog')->where('book_id','=',$bookId)->update($updateUseLog);


            }else{

                $addUseLog = [

                    'book_id' => $bookId,

                    'staff_id' => $nurse_id_one,

                    'staff_time' => time(),

                ];




                $log_id = Db::name('books_uselog')->insertGetId($addUseLog);

            }


            Db::name('service_log_mini')->insertAll($addDataAll);
            $this->error = '核销中，等待客户确认中';
            return ['id'=>0];


    }

	//查询护理师当天的护理量数据
	public function getNurseDateCount($nurseId,$starTime,$endTime){

		$where = [];
		array_push($where,['nurse_id_one','=',$nurseId]);
		array_push($where,['create_time','>=',$starTime]);
		array_push($where,['create_time','<=',$endTime]);

		$nurseCount = Db::name('service_log')->distinct(true)->field('customer_id')->where($where)->count();

		return $nurseCount;
	}

	public function getPushCategoryArray(){
	    return [
	        [
	            'id'=>1,
	            'goodsName'=>'疤痘护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>8,
	            'goodsName'=>'面部护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>10,
	            'goodsName'=>'项目身体护理',
	            'percentage'=>6,
	        ],
	        [
	            'id'=>11,
	            'goodsName'=>'生命之源',
	            'percentage'=>6,
	        ],
			[
			    'id'=>4,
			    'goodsName'=>'经络通',
			    'percentage'=>6,
			],

	        [
	            'id'=>12,
	            'goodsName'=>'疏肝理气',
	            'percentage'=>6,
	        ]
	    ];
	}

	public function delservicelog(array $request): array
	{
        Db::startTrans();
        try {
            $servicelogId = $request['id'] ?? 0;
            if ($servicelogId == 0){
                throw new \Exception('数据格式错误');
            }

            $serviceLog = ServiceLog::where('id','=',$servicelogId)->field('service_id,create_time')->find();
            if(empty($serviceLog)){
                throw new \Exception('核销记录不存在');
            }
            $refundModel = new Refund();
            $orderVerfiy = $refundModel->orderVerfiy(5,$serviceLog['create_time']);
            if(!$orderVerfiy){
                throw new \Exception('超出可作废时间');
            }

            $service = Service::where('id',$serviceLog['service_id'])->find();
            if(!empty($service)){
                //次卡-核销记录作废，卡项回去-针对次卡
                if($service['service_type'] == 2 && $service['status'] != 1 ) {
                    $service->status=1;
                    $service->update_time =time();
                    $service->save();
                }
            }

            if($serviceLog->order_id >0){
                ShopOrderModel::where('id',$serviceLog->order_id)->update(['status'=>4]);
            }

            $serviceLog->is_cancel =  empty($request['shop_person_id'])?2:1;
            $serviceLog->cancel_uid =  $request['user_id'];
            $serviceLog->cancel_time = time();
            $serviceLog->save();

            Db::commit();
            $this->error = '服务记录作废成功';
            return [];

        }catch (\Exception $e){
            Db::rollback();
            $this->error = $e->getMessage();
            return [];
        }

	}


    public function changeService($request)
    {
        try {
            $end_time = $request['end_time'] ?? '';
            $service_id = $request['service_id'];
            $service_type = $request['service_type'];
            if(!in_array($service_type ,[1,2])){
                throw new \Exception("非法请求");
            }
            if($service_type == 1 && empty($end_time)){
                throw new \Exception("请选择延长时间");
            }
            if($request['service_type']==2){
                throw new \Exception("不能发起申请");
            }
            $service = Service::cache(true,60)->find($service_id);


            $where = [];
            array_push($where,['update_id','=',$service_id]);
            array_push($where,['sh_type','=','0']);
            $res = Db::name('update_log')->where($where)->select()->toArray();
            if($res){
                throw new \Exception("提交正在审核中，请勿重复提交！");
            }else{
                    if($request['service_type']==1){
                        $old = $service['end_time'];
                        $new = strtotime($end_time);
                        if($old >$new){
                            throw new \Exception("不可缩短时间!");
                        }
                    }
                    $insertDate = [
                        'type'        => 1,
                        'update_id'   => $request['service_id'],
                        'shop_id'     => $request['shop_id'] ?? '',
                        'old_date'    => date('Y-m-d',$old),
                        'new_date'    => date('Y-m-d',$new),
                        'creator_id'  => $request['user_id'],
                        'create_time' => time(),
                        'customer_id' => $request['customer_id'],
                    ];

                    $id = Db::name('update_log')->insertGetId($insertDate);

                    $this->error = '修改服务提交成功';
                    return ['id'=>$id];
            }
         } catch (\Exception $e) {
             $this->error = $e->getMessage();
             return [];
         }


    }


    public function auditList($request)
    {

        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];
        $shop_ids = $request['shopIds'] ?? '';

        if($shop_ids){
            array_push($where,['shop_id','in',$shop_ids]);
        }

        // echo "<pre>";
        // print_r($where);
        // exit;
        $dataCounts = Db::name('update_log')->where($where)->count();

        $update_list = Db::name('update_log')->where($where)->order('id desc')->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->select()->toArray();

        $shopIds = array_values(array_unique(array_column($update_list, 'shop_id')));

        $operatorIds = array_values(array_unique(array_column($update_list, 'creator_id')));

        //获取店铺数据
        $shopList = Db::name('shop')->where('shop_id', 'in', $shopIds)->column('shop_name', 'shop_id');

        //获取员工姓名
        $creatorList = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');

        $list = [];
        foreach ($update_list as $key => $value) {
            $one = [];
            if($value['type']==1){
                $type = '卡项';
                $name = Db::name('service')->where('id','=',$value['update_id'])->value('name');
            }

            $one['name'] = $name;

            $one['type'] = $type;

            $one['shop_id']      = $shopList[$value['shop_id']] ?? '';

            $one['old_date'] = $value['old_date'];

            $one['new_date'] = $value['new_date'];

            $one['sh_type'] = $value['sh_type'] == 0 ? '未审核' : '已审核';

            $one['create_time'] = $value['create_time'] ? date('Y-m-d',$value['create_time']) : '';

            $one['sh_time'] = $value['sh_time'] ? date('Y-m-d',$value['sh_time']) : '';

            $one['update_id'] = $value['update_id'];

            $one['id'] = $value['id'];

            $one['shop_id']      = $creatorList[$value['creator_id']] ?? '';

            $one['sh_id']      = $creatorList[$value['sh_id']] ?? '';

            array_push($list,$one);
        }

        /**总数统计**/
        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCounts ?? 0;
        return $data;
    }

    public function submitAudit($request)
    {
//        $this->error = '暂停审核，请等待通知';
//        return [];
        Db::startTrans();
        try {
            $id = $request['id'] ?? '';
            if(empty($id)){
                throw new \Exception("非法请求");
            }
            $update_info = Db::name('update_log')->where('id',$id)->field('update_id,type,old_date,new_date,id')->find();
            if(!empty($update_info)){
                $service_id = $update_info['update_id']; //服务卡项id
                $end_time = $update_info['new_date'];

                $service = Service::find($service_id);

                if($service->service_type == 2){
                    throw new \Exception("次卡无法审核");
                }

                if($service->end_time >strtotime($end_time)){
                    throw new \Exception("延长时间小于卡项结束时间，无法审核通过");
                }
                if($service->end_time == strtotime($end_time)){
                    throw new \Exception("延长时间等于卡项结束时间，无需审核");
                }


                $service->status = strtotime($end_time) <= time() ?'2':'1';

                $data_u = [
                    'sh_id'   => $request['user_id'],
                    'sh_time' => time(),
                    'sh_type' => '1'
                ];
                $id_u = Db::name('update_log')->where('id',$id)->update($data_u);
                if(!$id_u){
                    throw new \Exception("审核失败，请稍后重试");
                }

                $half_num = 3; //大于15天，则是3
                $month_max = 6; //整月是6

                $insert = [
                    'service_id'=>$service->id,
                    'update_log_id'=>$update_info['id'],
                    'shop_id'=>$service->shop_id,
                    'customer_id'=>$service->customer_id,
                    'new_begin_time'=>time(),
                    'new_end_time'=>strtotime($end_time),
                    'create_time'=>time(),
                ];
                $residue_bj = $residue_zj = $residue_dz = 0;  //剩余消耗本金、赠金、店转

                if($service->overtime_num >0){
                    //不首次延长
                    $map =[
                        ['service_id','=',$service->id],
                        ['customer_id','=',$service->customer_id]
                    ];
                    $overtime_log = DB::name('service_overtime_log')->where($map)->order('id','desc')->find();
                    $insert['old_begin_time'] =  $overtime_log['new_begin_time'];
                    $insert['old_end_time'] =  $overtime_log['new_end_time'];
                    if($overtime_log['kk_money'] >0){
                        $begin_time = $overtime_log['new_begin_time'];
                        $end_time = $overtime_log['new_end_time'];
                        $map =[
                            ['is_cancel','<>',2],
                            ['create_time','between',"$begin_time,$end_time"],
                            ['service_id','=',$service->id],
                            ['customer_id','=',$service->customer_id]
                        ];
                        $end_time = date('Y-m-d',$end_time);
                        $consume_count = ServiceLog::where($map)->count();
                        $bj = $overtime_log['consume_money'];
                        $zj = $overtime_log['consume_gratuity'];
                        $dz = $overtime_log['consume_store_transfer'];
                        $service_max_num = $overtime_log['service_max_num'];
                        $one_bj = $service_max_num >0?bcdiv($bj,$service_max_num,2):0; //单次消耗本金,
                        $one_zj = $service_max_num >0?bcdiv($zj,$service_max_num,2):0; //单次消耗赠金
                        $one_dz = $service_max_num >0?bcdiv($dz,$service_max_num,2):0; //单次消耗店转
                        $residue_bj = $consume_count >0 ? bcsub($bj,bcmul($consume_count,$one_bj,2),2):$bj; //剩余本金
                        $residue_zj = $consume_count >0 ? bcsub($zj,bcmul($consume_count,$one_zj,2),2):$zj; //剩余赠金
                        $residue_dz = $consume_count >0 ? bcsub($dz,bcmul($consume_count,$one_dz,2),2):$dz; //剩余店转
                    }
                }else{
                    //首次延长
                    $insert['old_begin_time'] = $service->start_time;
                    $insert['old_end_time']   = $service->end_time;

                    if($service->kk_money > 0){
                        $map =[
                            ['is_cancel','<>',2],
                            ['service_id','=',$service->id],
                            ['customer_id','=',$service->customer_id]
                        ];
                        $consume_count = ServiceLog::where($map)->count();
                        $bj = $service->consume_money;
                        $zj = $service->consume_gratuity;
                        $dz = $service->consume_store_transfer;
                        $service_max_num = $service->service_max_num;
                        $one_bj = $service_max_num >0?bcdiv($bj,$service_max_num,2):0; //单次消耗本金,
                        $one_zj = $service_max_num >0?bcdiv($zj,$service_max_num,2):0; //单次消耗赠金
                        $one_dz = $service_max_num >0?bcdiv($dz,$service_max_num,2):0; //单次消耗店转
                        $residue_bj = $consume_count >0 ? bcsub($bj,bcmul($consume_count,$one_bj,2),2):$bj; //剩余本金
                        $residue_zj = $consume_count >0 ? bcsub($zj,bcmul($consume_count,$one_zj,2),2):$zj; //剩余赠金
                        $residue_dz = $consume_count >0 ? bcsub($dz,bcmul($consume_count,$one_dz,2),2):$dz; //剩余店转
                    }
                }

                $insert['consume_store_transfer'] = $residue_dz; //消耗店转
                $insert['consume_gratuity'] = $residue_zj;   //消耗赠金
                $insert['consume_money'] = $residue_bj;  //消耗本金
                $insert['kk_money'] = bcadd($residue_bj,bcadd($residue_zj,$residue_dz,2),2); //剩余开卡金额

                $shopModel = new Order();
                $enterShopData = $shopModel->getMaxCustomerEnterShop($insert['new_begin_time'],$insert['new_end_time'],$half_num,$month_max); //最高进店次数
                $insert['service_max_num'] = $enterShopData['service_max_num'];
                $insert['first_month_max_service_num'] = $enterShopData['shou'];
                $insert['middle_month_max_service_num'] = $enterShopData['zhong'];
                $insert['end_month_max_service_num'] = $enterShopData['wei'];

                $add_res = Db::name('service_overtime_log')->insert($insert);
                if(!$add_res){
                    throw new \Exception("变更记录添加失败，请稍后重试");
                }

                $service->overtime_num = bcadd($service->overtime_num,1);
                $service->end_time = strtotime($end_time);
                $service_res = $service->save();
                if(!$service_res){
                    throw new \Exception("卡项修改失败，请稍后重试");
                }

                Db::commit();
                $this->error = '审核成功';
                return ['msg'=>'审核成功'];
            }else{
                throw new \Exception("审核记录不存在");
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return [];
        }
    }
     /**
     * 获取护理列表汇总
     */

     public function getTotalData(array $request): array
     {

         $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

         $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;


         $shopId = isset($request['shopId']) && intval($request['shopId']) ? intval($request['shopId']) : 0;

         $is_export = isset($request['export']) && intval($request['export']) ? intval($request['export']) : 0;

         $shopIds = $request['shopIds'] ?? [];

         $nowYear =  date('y'); //当前年
         $nowMonth =  date('m'); //当前月份
         $nowdata =  date('t'); //当前天数

         $startmonth = $nowYear.'-'.$nowMonth.'-'.'1';
         $endmonth = $nowYear.'-'.$nowMonth.'-'.$nowdata;

         $start_time = $request['start_time'] ?? '';
         if($start_time){

             $startTimeToday =strtotime($request['start_time']);
         }else{
             $startTimeToday =strtotime($startmonth);
         }

         $endTime = $request['endTime'] ?? '';

         if($endTime){

             $endTimeToday =strtotime($request['endTime'])+86399;
             $startDataTime = strtotime($request['endTime']);
             $endDataTime = strtotime($request['endTime'])+86399;

         }else{
             $endTimeToday =strtotime($endmonth)+86399;
             $startDataTime = strtotime(date('Y-m-d'));
             $endDataTime = strtotime(date('Y-m-d'))+86399;
         }

         $where      = [];

         $shopId && array_push($where, ['s.shop_id', '=', $shopId]);

         if($shopIds){

             array_push($where,['s.shop_id','in',$shopIds]);

         }

         $nurseName = $request['nurse_name'] ?? '';

         if($nurseName){

             array_push($where,['s.name','=',$nurseName]);

         }

         $category =$this->getPushCategoryArray();
         array_push($where, ['s.status', '<>', 3]);
         //array_push($where, ['sp.type', '=', 1]);

         // $dataCount = Db::name('shop_person')->alias('s')
         // 	    ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')
         // 	    ->where($where)->count();

         /*
             疤痘护理---- 1  | 面部护理---- 8 | 项目身体护理  ---10  | 生命之源/经络通/疏肝理气 --11 | 基础补水 --12
         */



             $field = ['s.id,s.shop_id,s.shop_name,s.name,s.market_name,s.station_name'];

             if($is_export == '1'){

                 $list  = Db::name('shop_person')->alias('s')

                     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                     ->where($where)

                     ->field($field)->order('s.shop_id DESC')

                     ->select()->toArray();

             }else{

                 $list  = Db::name('shop_person')->alias('s')

                     ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                     ->where($where)

                     ->field($field)->order('s.shop_id DESC')

                     ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                     ->select()->toArray();

             }

             $list  = Db::name('shop_person')->alias('s')

                 ->join('shop sp', 's.shop_id=sp.shop_id', 'LEFT')

                 ->where($where)

                 ->field($field)->order('s.shop_id DESC')

                 // ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                 ->select()->toArray();

             $pids =array_column($list,'id');
             $category =$this->getPushCategoryArray();
             $ids =array_column($category,'id');

             // 获取当天服务量
             // 比例为1的
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['nurse_id_two','=',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr1 =Db::name('service_log')
                 ->field('count(*) as total,category_id')
                 ->where($where)
                 ->group('category_id')
                 ->select()->toArray();
             //print_r($arr1);
             // 比例为0.5的
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['nurse_id_two','>',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr2 =Db::name('service_log')
             ->field('count(*) as total,category_id')
             ->where($where)
             ->group('category_id')
                 ->select()->toArray();
             $where = [];
             array_push($where,['category_id','in',$ids]);
             array_push($where,['nurse_id_two','in',$pids]);
             array_push($where,['nurse_id_one','>',0]);
             array_push($where,['create_time','between',"$startTimeToday,$endTimeToday"]);
             $arr3 =Db::name('service_log')
             ->field('count(*) as total,category_id')
             ->where($where)
             ->group('category_id')
                 ->select()->toArray();
             $result = array();
             foreach($arr1 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total'];
                 }else{
                     $result[$val['category_id']] += $val['total'];
                 }
             }
             foreach($arr2 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total']*0.5;
                 }else{
                     $result[$val['category_id']] += $val['total']*0.5;
                 }
             }
             foreach($arr3 as $val)
             {
                 if(!isset($result[$val['category_id']]))
                 {
                     $result[$val['category_id']] = $val['total']*0.5;
                 }else{
                     $result[$val['category_id']] += $val['total']*0.5;
                 }
             }
             $huliTotal=0;
             $data = array();
             $data = [
                 'id'=>0,
                 'shop_id'=>0,
                 'shop_name'=>"",
                 'name'=>'',
                 'market_name'=>"汇总",
                 'station_name'=>"",
                 'bahennum'=>0,
                 'jichubushui'=>0,
                 'total'=>0,
                 'daycount'=>0,
                 'mianbunum'=>0,
                 'shentinum'=>0,
                 'shengming'=>0,
                 'jingluotong'=>0,
                 'shuganliqi'=>0
             ];
             foreach($result as $key => $val)
             {
                 if($key == 1){
                     $data['bahennum'] = $val;
                     $huliTotal += $val;
                 }
                 if($key == 4){
                     $data['jingluotong'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 8){
                     $data['mianbunum'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 10){
                     $data['shentinum'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 11){
                     $data['shengming'] = $val;
                     $huliTotal += $val;
                 }

                 if($key == 12){
                     $data['shuganliqi'] = $val;
                     $huliTotal += $val;
                 }
             }
             $where = [];

             array_push($where,['nurse_id_one','in',$pids]);
             array_push($where,['create_time','>=',$startDataTime]);
             array_push($where,['create_time','<=',$endDataTime]);

             $nurseCount = Db::name('service_log')->distinct(true)->field('customer_id')->where($where)->count();

             //基础补水 没有办法归类暂时不做计算  2022-04-18
             $data['jichubushui'] = 0;
             $data['total'] = $huliTotal;
             $data['daycount'] = $nurseCount;




         return $data;

     }
}
